package com.ysfxt.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysfxt.auth.AuthContextHolder;
import com.ysfxt.constant.RedisConst;
import com.ysfxt.exception.YsfxtException;
import com.ysfxt.jwt.JwtHelper;
import com.ysfxt.listener.ExcelListener;
import com.ysfxt.model.SysTeacher;
import com.ysfxt.mapper.SysTeacherMapper;
import com.ysfxt.result.Result;
import com.ysfxt.result.ResultCodeEnum;
import com.ysfxt.service.SysTeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysfxt.utils.MD5;
import com.ysfxt.vo.TeacherParam;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ysfxt
 * @since 2024-03-29
 */
@Service
public class SysTeacherServiceImpl extends ServiceImpl<SysTeacherMapper, SysTeacher> implements SysTeacherService {
    
    
    @Resource
    private SysTeacherMapper sysTeacherMapper;
    
    @Resource
    private RedisTemplate redisTemplate;
    
    /**
     * 条件查询
     * @param teacherParam
     * @return
     */
    @Override
    public Result select(TeacherParam teacherParam) {
        LambdaQueryWrapper<SysTeacher> wrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(teacherParam.getCollege())){
            wrapper.like(SysTeacher::getCollege,teacherParam.getCollege());
        }
        if(teacherParam.getIdentity()!=null){
            wrapper.eq(SysTeacher::getIdentity,teacherParam.getIdentity());
        }
        if(teacherParam.getScope()!=null){
            wrapper.eq(SysTeacher::getScope,teacherParam.getScope());
        }
        IPage<SysTeacher> page =new Page<>(teacherParam.getPageNum(), teacherParam.getPageSize());
        sysTeacherMapper.selectPage(page, wrapper);
        page.getRecords().stream().forEach(item->{
            item.setIdentityString(item.getIdentity().getComment());
            item.setScopeString(item.getScope().getComment());
        });
        return Result.ok(page);
    }
    
    /**
     * 账号新增
     * @param sysTeacher
     * @return
     */
    @Override
    public Result saveTeacher(SysTeacher sysTeacher) {
        LambdaQueryWrapper<SysTeacher> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(SysTeacher::getAccount, sysTeacher.getAccount());
        Integer sum = sysTeacherMapper.selectCount(wrapper);
        if(sum>0){
            return Result.build(null,505, "账号已被使用。");
        }
        sysTeacher.setPassword(MD5.encrypt(sysTeacher.getPassword()));
        sysTeacher.setGmtCreate(new Date());
        sysTeacher.setGmtModified(new Date());
        sysTeacherMapper.insert(sysTeacher);
        return Result.ok();
    }
    
    /**
     * 导出
     * @param response
     * @return
     */
    @Override
    public Result exportData(HttpServletResponse response) {
        try {
            //设置响应头信息和其他信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String fileName = URLEncoder.encode("账号信息", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //查询所有数据
            List<SysTeacher> sysTeachers =new ArrayList<>();
            //写出
            EasyExcel.write(response.getOutputStream(), SysTeacher.class)
                    .sheet("账号信息").doWrite(sysTeachers);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            throw new YsfxtException(ResultCodeEnum.DATA_ERROR);
        }
    }
    
    /**
     * 导入
     * @param file
     */
    @Override
    public void importData(MultipartFile file) {
        //监听器
        ExcelListener<SysTeacher> excelListener= new ExcelListener(sysTeacherMapper);
        try {
            EasyExcel.read(file.getInputStream(),SysTeacher.class,excelListener)
                    .sheet().doRead();
        }catch (Exception e) {
            e.printStackTrace();
            throw new YsfxtException(ResultCodeEnum.DATA_ERROR);
        }
    }
    
    /**
     * 登录
     * @param s
     * @return
     */
    @Override
    public Result login(SysTeacher s) {
        LambdaQueryWrapper<SysTeacher> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(SysTeacher::getAccount, s.getAccount());
        wrapper.eq(SysTeacher::getPassword, MD5.encrypt(s.getPassword()));
        SysTeacher teacher = sysTeacherMapper.selectOne(wrapper);
        if(teacher==null)
            return Result.fail("账号或密码错误");
        String token = JwtHelper.createToken(teacher.getId(), RedisConst.USER_LOGIN_KEY_PREFIX);
        teacher.setPassword("");
        redisTemplate.opsForValue()
                .set(RedisConst.USER_LOGIN_KEY_PREFIX+teacher.getId(),
                        teacher,
                        RedisConst.USERKEY_TIMEOUT,
                        TimeUnit.DAYS);
        Map<String,Object> map = new HashMap<>();
        map.put("user",teacher);
        map.put("token",token);
        return Result.ok(map);
    }
    
    /**
     * 修改密码
     * @param sysTeacher
     * @return
     */
    @Override
    public Result setPassword(SysTeacher sysTeacher) {
        Long teacherId = AuthContextHolder.getTeacherId();
        sysTeacher.setId(teacherId);
        sysTeacher.setPassword(MD5.encrypt(sysTeacher.getPassword()));
        sysTeacher.setGmtModified(new Date());
        sysTeacherMapper.updateById(sysTeacher);
        return Result.ok();
    }
}
